import KeyValue from "@/domain/KeyValue";
import { webStorageService } from "@/global/BeanFactory";
import FileListItem from "@/module/driver/domain/FileListItem";
import DefaultDriver from "@/module/driver/impl/DefaultDriver";
import WebDavDriver from "@/module/driver/impl/WebDavDriver";
import SettingOrderEnum from "@/module/setting/enumeration/SettingOrderEnum";
import { useLocalSettingStore } from "@/module/setting/store/LocalSettingStore";
import WebStorage from "@/module/storage/entity/WebStorage";
import StorageTypeEnum from "@/module/storage/enumeration/StorageTypeEnum";
import { useLoadingStore } from "@/store/LoadingStore";
import MessageUtil from "@/utils/MessageUtil";
import { defineStore } from "pinia";

export const useBrowserStore = defineStore('browser', {
    state: () => ({
        path: '/',
        paths: new Array<string>(),
        items: new Array<FileListItem>(),
        storage: {} as WebStorage,
        driver: new DefaultDriver()
    }),
    getters: {
        back: (state) => state.paths.length > 0,
        pathSplit: (state): Array<KeyValue<string, string>> => {
            let items = state.path.split('/');
            let paths = new Array<KeyValue<string, string>>();
            let prefix = '';
            for (let item of items) {
                if (item.trim() === '') {
                    continue;
                }
                prefix = prefix + '/' + item.trim();
                paths.push({
                    key: item,
                    value: prefix
                });
            }
            return paths;
        },
        up: (state): boolean => state.path && state.path !== '/' ? true : false,
        link: (state): boolean => {
            switch (state.storage.type) {
                case StorageTypeEnum.WEBDAV:
                    return true;
                default:
                    return false;
            }
        }
    },
    actions: {
        resolve(name: string) {
            if (this.path.length > 1) {
                return this.path + '/' + name;
            } else {
                return '/' + name;
            }
        },
        init(id: string): boolean {
            // 数据初始化
            this.path = '/';
            this.paths = new Array<string>();
            this.items = new Array<FileListItem>();
            // 获取文件
            let storage = webStorageService.info(id);
            if (!storage) {
                return false;
            }
            this.storage = storage;
            // 判断类型
            if (storage.type === StorageTypeEnum.WEBDAV) {
                this.driver = new WebDavDriver(this.storage.webdav);
            }
            return true;
        },
        to(path: string) {
            this.paths.push(this.path);
            this.path = path;
            this.render();
        },
        render() {
            useLoadingStore().start("正在获取目录信息");
            this.driver.list(this.path)
                .then(items => {
                    let order = useLocalSettingStore().order;
                    if (order === SettingOrderEnum.DEFAULT) {
                        this.items = items;
                    } else if (order === SettingOrderEnum.NAME_ASC) {
                        this.items = items.sort((a, b) => {
                            return a.name.localeCompare(b.name, 'zh-CN');
                        });
                    } else if (order === SettingOrderEnum.NAME_DESC) {
                        this.items = items.sort((a, b) => {
                            return b.name.localeCompare(a.name, 'zh-CN');
                        });
                    } else if (order === SettingOrderEnum.UPDATE_TIME_ASC) {
                        this.items = items.sort((a, b) => {
                            return new Date(a.updateTime).getTime() -
                                new Date(b.updateTime).getTime();
                        });
                    } else if (order === SettingOrderEnum.UPDATE_TIME_DESC) {
                        this.items = items.sort((a, b) => {
                            return new Date(b.updateTime).getTime() -
                                new Date(a.updateTime).getTime();
                        });
                    } else if (order === SettingOrderEnum.TYPE) {
                        this.items = items.sort((a, b) => {
                            return a.extra.localeCompare(b.extra, 'zh-CN');
                        });
                    }
                })
                .catch(e => {
                    MessageUtil.error("文件列表获取失败", e);
                    this.items = [];
                })
                .finally(() => useLoadingStore().close());
        },
        pre() {
            if (this.paths.length == 0) {
                return;
            }
            this.path = this.paths.pop() || '/';
            this.render();
        },
        home() {
            this.path = '/';
            this.paths = new Array<string>();
            this.render();
        },
        toUp() {
            let index = this.path.lastIndexOf('/');
            if (index > -1) {
                if (index === 0) {
                    this.to('/');
                } else {
                    this.to(this.path.substring(0, index));
                }
            }
        },
    }
})